package router

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm/utils"
	"manboge/conf"
	"manboge/mid"
	"manboge/service"
	"manboge/util"
	"net/http"
	"time"
)

func NewRouter() *gin.Engine {
	r := gin.Default()
	r.Use(mid.Cors())

	r.Use(mid.AccessControlMiddleware()).StaticFS("/static", http.Dir("./static"))

	v1 := r.Group("/")
	{
		v1.GET("ping", func(context *gin.Context) {
			context.JSON(http.StatusOK, gin.H{
				"code": 200,
				"msg":  "成功",
			})
		})

		v1.POST("upload/:filename", func(context *gin.Context) {
			file, _, err := context.Request.FormFile("file")
			if err != nil {
				util.LogrusObj.Error("Error getting file from request: ", err)
				context.JSON(http.StatusBadRequest, gin.H{
					"code": 400,
					"msg":  "Failed to get the file from the request",
				})
				return
			}

			filename := context.Param("filename")
			if file == nil {
				util.LogrusObj.Warn("No file uploaded for filename: ", filename)
				context.JSON(http.StatusBadRequest, gin.H{
					"code": 400,
					"msg":  "No file uploaded",
				})
				return
			}

			filePath, err := service.UploadArticleToLocalStaticByResize(file, utils.ToString(time.Now().Unix()), utils.ToString(time.Now().Unix()%1000))
			if err != nil {
				util.LogrusObj.Error("Error uploading file: ", err)
				context.JSON(http.StatusInternalServerError, gin.H{
					"code": 500,
					"msg":  "File upload failed",
				})
				return
			}

			util.LogrusObj.Info("File uploaded successfully, path: ", filePath)
			context.JSON(http.StatusOK, gin.H{
				"path": conf.Host + conf.HttpPort + conf.ArticlePath + filePath,
				"code": 200,
			})
		})

		v1.POST("delete/:filename", func(context *gin.Context) {
			filename := context.Param("filename")
			err := service.DeleteFile(filename)
			if err != nil {
				util.LogrusObj.Error("Error deleting file: ", err)
				context.JSON(http.StatusInternalServerError, gin.H{
					"code": 500,
					"msg":  "Failed to delete file",
				})
				return
			}

			util.LogrusObj.Info("File deleted successfully, filename: ", filename)
			context.JSON(http.StatusOK, gin.H{
				"msg":  "File deleted successfully",
				"code": 200,
			})
		})
	}

	return r
}
